# -*- coding: utf-8 -*-
import json
from datetime import time

import jsonpath
import numpy as np
import pandas as pd

def readjson():
    list_main = []
    #读取JSON并转化为转化为LIST
    with open("events_World_Cup.json",encoding='utf-8') as f:
        data = f.read()
        data = "{\"data\":" + data + "}"
        print (json.dumps(data, sort_keys=True, indent=2)) # 排序并且缩进两个字符输出
        js = json.loads(data)
        lista =jsonpath.jsonpath(js, '$..data[*]')
        print("a")

        for item_lista in lista:
            eventId = jsonpath.jsonpath(item_lista, '$..eventId')[0]
            subEventName = jsonpath.jsonpath(item_lista, '$..subEventName')[0]
            tags = jsonpath.jsonpath(item_lista, '$..tags')[0]
            playerId = jsonpath.jsonpath(item_lista, '$..playerId')[0]
            positions = jsonpath.jsonpath(item_lista, '$..positions')[0]
            matchId = jsonpath.jsonpath(item_lista, '$..matchId')[0]
            eventName = jsonpath.jsonpath(item_lista, '$..eventName')[0]
            teamId = jsonpath.jsonpath(item_lista, '$..teamId')[0]
            matchPeriod = jsonpath.jsonpath(item_lista, '$..matchPeriod')[0]
            eventSec = jsonpath.jsonpath(item_lista, '$..eventSec')[0]
            subEventId = jsonpath.jsonpath(item_lista, '$..subEventId')[0]
            id = jsonpath.jsonpath(item_lista, '$..id')[0]
            list_main.append([matchId,matchPeriod,teamId,eventName,eventSec,subEventId,id,eventId,subEventName,tags,playerId,positions])

    #将LIST保存为CSV文件
    df_main = pd.DataFrame(list_main,columns=["matchId","matchPeriod","teamId","eventName","eventSec","subEventId","id","eventId","subEventName","tags","playerId","positions"])
    df_main.to_csv("main.csv",index=False)

def readcsv():
    #读取CSV文件
    df_main = pd.read_csv("main.csv")
    df_main=df_main.fillna(value='')
    #取出不同的matchId
    difmatchid = df_main['matchId'].unique()
    dic_out ={}
    for item_matchid in difmatchid:
        dic_match = []
        #筛选当前matchId的数据
        df_filter_matchid = df_main[df_main['matchId'] == item_matchid]
        # 取出不同的matchPeriod
        difmatchPeriod = df_filter_matchid['matchPeriod'].unique()
        for item_matchPeriod in difmatchPeriod:
            df_filter_matchPeriod = df_filter_matchid[df_filter_matchid['matchPeriod'] == item_matchPeriod]

            difteamid = df_filter_matchPeriod['teamId'].unique()
            for item_teamid in difteamid:
                df_filter_teamid = df_filter_matchPeriod[["eventId","subEventName","tags","playerId","positions","matchId","eventName","teamId","matchPeriod","eventSec","subEventId","id"]][df_filter_matchPeriod['teamId'] == item_teamid]

                df_filter_teamid_sort = df_filter_teamid.sort_values(by=['eventSec'],ascending=True)
                df_filter_teamid_sort['xh'] = 0

                shijian = 0
                fenlei =0
                for index,row in df_filter_teamid_sort.iterrows():
                    shijian2 = row['eventSec']

                    if float(shijian2) -float(shijian) < 10:
                        df_filter_teamid_sort.loc[index,'xh'] = fenlei
                        shijian
                    else:
                        fenlei = fenlei + 1
                        df_filter_teamid_sort.loc[index, 'xh'] = fenlei
                    shijian = shijian2

                difsec = df_filter_teamid_sort['xh'].unique()
                for item_sec in difsec:
                    dic_main = {}
                    df_output = df_filter_teamid_sort[["eventId","subEventName","tags","playerId","positions","matchId","eventName","teamId","matchPeriod","eventSec","subEventId","id"]][df_filter_teamid_sort['xh']==item_sec]
                    df_output = df_output.reset_index()
                    if len(df_output)>0:
                        dic_main['matchId'] = str(item_matchid)
                        dic_main['matchPeriod'] = str(item_matchPeriod)
                        dic_main['teamId'] = str(item_teamid)
                        dic_main['beginTime'] = df_output.loc[0,'eventSec']
                        dic_main['phaseLength'] = len(df_output)
                        dic_main['eventList'] = df_output.to_dict(orient='records')
                        if len(df_output)>=3:
                            dic_match.append(dic_main)
                            

        dic_out[str(item_matchid)] = dic_match

    # dumps 将数据转换成字符串
    info_json = json.dumps(dic_out, sort_keys=False, indent=4, separators=(',', ': '))
    info_json = info_json.replace("NaN","")
    info_json = info_json.replace("\"tags\": \"", "\"tags\": ")
    info_json = info_json.replace("\"positions\": \"", "\"positions\": ")
    info_json = info_json.replace("]\"", "]")
    info_json = info_json.replace("'", "\"")
    f = open('info.json', 'w')
    f.write(json.dumps(json.loads(info_json)))

def readcsv1():
    #读取CSV文件

    dic_mainm = {}
    df_mainm = pd.read_csv("main.csv")
    df_mainm=df_mainm.fillna(value='')
    df_mainm['xh'] =0
    matchId=""
    matchPeriod=""
    teamId=""
    shijian=0
    fenlei = 0

    # 取出不同的matchId
    difmatchid = df_mainm['matchId'].unique()
    for item_matchid in difmatchid:
        dic_out={}
        df_main = df_mainm[df_mainm['matchId'] == item_matchid]
        for index,row in df_main.iterrows():
            
            matchId2 = row['matchId']
            matchPeriod2 = row['matchPeriod']
            teamId2 = row['teamId']
            shijian2 = row['eventSec']

            if matchId2 != matchId or matchPeriod2 != matchPeriod or teamId2 != teamId or float(shijian2) -float(shijian) > 10:
                fenlei = fenlei + 1
                df_main.loc[index, 'xh'] = fenlei
            else:
                df_main.loc[index, 'xh'] = fenlei

            matchId = matchId2
            matchPeriod = matchPeriod2
            teamId = teamId2
            shijian = shijian2

        difsec = df_main['xh'].unique()
        for item_sec in difsec:
            dic_match = []
            dic_main = {}
            df_output = df_main[
                ["eventId", "subEventName", "tags", "playerId", "positions", "matchId", "eventName", "teamId",
                 "matchPeriod", "eventSec", "subEventId", "id"]][df_main['xh'] == item_sec]
            df_output = df_output.reset_index()
            if len(df_output) > 0:
                dic_main['matchId'] = df_output.loc[0,'matchId']
                dic_main['matchPeriod'] = df_output.loc[0,'matchPeriod']
                dic_main['teamId'] = df_output.loc[0,'teamId']
                dic_main['beginTime'] = df_output.loc[0, 'eventSec']
                dic_main['phaseLength'] = len(df_output)
                dic_main['eventList'] = df_output.to_dict(orient='records')
                if len(df_output) >= 3:
                    dic_match.append(dic_main)
                    
            if len(dic_match)>0:
                dic_out['phase{}'.format(item_sec)] = dic_match
        dic_mainm[str(item_matchid)] = dic_out
    # dumps 将数据转换成字符串
    info_json = json.dumps(dic_mainm, sort_keys=False, indent=4, separators=(',', ': '), cls=MyEncoder)
    info_json = info_json.replace("\"tags\": \"", "\"tags\": ")
    info_json = info_json.replace("\"positions\": \"", "\"positions\": ")
    info_json = info_json.replace("]\"", "]")
    info_json = info_json.replace("'", "\"")
    f = open('info.json', 'w')
    f.write(json.dumps(json.loads(info_json), cls=MyEncoder))


class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return float(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, time):
            return obj.__str__()

if __name__ == '__main__':
    
    readcsv1()
